package com.wd.mylibrary_square.view.activity


import android.widget.ImageView

import cn.jzvd.Jzvd
import cn.jzvd.JzvdStd
import android.Manifest
import android.content.pm.PackageManager
import android.os.Build

import android.view.SurfaceView
import android.view.View
import android.widget.FrameLayout
import android.widget.Toast
import androidx.core.app.ActivityCompat

import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.bumptech.glide.Glide
import com.wd.mylibrary_base.base.BaseActivity
import com.wd.mylibrary_base.bean.WatchBean
import com.wd.mylibrary_base.utils.MyApp
import com.wd.mylibrary_square.R
import com.wd.mylibrary_square.databinding.ActivityWatchBinding
import com.wd.mylibrary_square.viewmodel.WatchViewModel
import io.agora.rtc2.ChannelMediaOptions
import io.agora.rtc2.Constants
import io.agora.rtc2.IRtcEngineEventHandler
import io.agora.rtc2.RtcEngine
import io.agora.rtc2.RtcEngineConfig
import io.agora.rtc2.video.VideoCanvas
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException



@Route(path = "/Square/Watch")

class WatchActivity : BaseActivity<WatchViewModel,ActivityWatchBinding>(R.layout.activity_watch) {
    var liveId=0
    var liveStatus=1
    var liveTitle=""
    var headPic=""
    var nickName=""
    var anchorId=0
    var follow=1
    var liveCoverUrl=""

    // 填写声网控制台中获取的 App ID
    private val appId = "8fe3959de1e048e693a355c96a98f72f"

    // 填写频道名
    private val channelName = "zhiBo"

    // 填写声网控制台中生成的临时 Token
    private val token = "007eJxTYKhROseavfbgr16Fv8l/u/gXMRewXD362efq7Gvz1rz78H+PAoNFWqqxpallSqphqoGJRaqZpXGisalpsqVZoqVFmrlR2lGeb2kNgYwMrNz6DIxQCOYzVGVkOuUzMAAAT0IiDg=="

    private val PERMISSION_REQ_ID = 22

    private var options: ChannelMediaOptions? = null

    override fun initView() {
        liveId=intent.getIntExtra("liveId",0)
        liveStatus=intent.getIntExtra("liveStatus",0)
        follow=intent.getIntExtra("follow",0)
        anchorId=intent.getIntExtra("anchorId",0)
        liveCoverUrl=intent.getStringExtra("liveCoverUrl").toString()
        liveTitle=intent.getStringExtra("liveTitle").toString()
        headPic=intent.getStringExtra("headPic").toString()
        nickName=intent.getStringExtra("nickName").toString()

        var sessionId = MyApp.sp.getString("sessionId", "").toString()
        var userId = MyApp.sp.getInt("userId",0)

        if(liveStatus==1){

            if(checkPermissions()){
                initRtcEngine()
                viewModel.getWatchData(userId,sessionId,liveId)
            }else{
                // 如果已经授权，则初始化 RtcEngine 并加入频道
                ActivityCompat.requestPermissions(this, getRequiredPermissions(), PERMISSION_REQ_ID);
                initRtcEngine()
            }
        }else{
            dataBinding.sv.visibility=View.VISIBLE
            var url="http://10.59.9.24/live-platform/recordVideo/${liveId}"
            dataBinding.video.setUp(url,true,liveTitle)
            dataBinding.video.startPlayLogic()
        }

        dataBinding.edi.alpha=0.6f

    }

    override fun dataObserve() {

//        开始音视频互动
        dataBinding.lianMai.setOnClickListener {

            dataBinding.sv.visibility=View.VISIBLE
            //初始化视频
            startVideo()
        }

        viewModel.watchData.observe(this,{
            Toast.makeText(this, it.message, Toast.LENGTH_SHORT).show()

            if(it.result!=null){
                dataBinding.video.setUp(it.result.liveStreamUrl,true,liveTitle)
                dataBinding.video.startPlayLogic()
                //声网看直播
                initializeAndJoinChannel(it.result)
            }
        })
    }

    private var mRtcEngine: RtcEngine? = null

    // 实现 IRtcEngineEventHandler 接口的方法
    private val mRtcEventHandler = object : IRtcEngineEventHandler() {

        override fun onJoinChannelSuccess(channel: String?, uid: Int, elapsed: Int) {
            super.onJoinChannelSuccess(channel, uid, elapsed)

            // 成功加入频道回调
            runOnUiThread {
                Toast.makeText(
                    this@WatchActivity,
                    "Join channel success",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }

        // 远端用户或主播加入当前频道回调
        override fun onUserJoined(uid: Int, elapsed: Int) {
            super.onUserJoined(uid, elapsed)

            runOnUiThread {
                // 当远端用户加入频道后，显示指定 uid 的远端视频流
                setupRemoteVideo(uid)
            }
        }

        // 远端用户或主播离开当前频道回调
        override fun onUserOffline(uid: Int, reason: Int) {
            super.onUserOffline(uid, reason)
            runOnUiThread {
                Toast.makeText(
                    this@WatchActivity,
                    "User offline: $uid",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }

    }

    private var myType: Int = 0


    private fun initializeAndJoinChannel(lookLive: WatchBean.Result) {
        options = ChannelMediaOptions()
        if(myType==104){
            mRtcEngine?.setClientRole(Constants.CLIENT_ROLE_AUDIENCE)
            mRtcEngine?.setChannelProfile(Constants.CHANNEL_PROFILE_LIVE_BROADCASTING)
            val container = findViewById<FrameLayout>(R.id.fl)
            val surfaceView = SurfaceView(baseContext)
            surfaceView.setZOrderMediaOverlay(true)
            container.addView(surfaceView)
            // 将 SurfaceView 对象传入声网实时互动 SDK，设置远端视图
            mRtcEngine!!.setupRemoteVideo(VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_FIT, 0))
            // 开启本地预览
            mRtcEngine?.startPreview()
        }else{
            mRtcEngine?.setClientRole(Constants.CLIENT_ROLE_AUDIENCE)
        }
// 发布麦克风采集的音频
        //options?.publishMicrophoneTrack = true;
        // 发布摄像头采集的视频
        options?.publishCameraTrack = true;
        // 自动订阅所有音频流
        options?.autoSubscribeAudio = true;
        // 自动订阅所有视频流
        options?.autoSubscribeVideo = true;
        // 使用临时 Token 和频道名加入频道，uid 为 0 表示引擎内部随机生成用户名

        // 成功后会触发 onJoinChannelSuccess 回调
        //settingLiveType(Constants.CLIENT_ROLE_AUDIENCE,viewModel.agoraToken)
//        mRtcEngine?.joinChannel(
//            lookLive.,
//            lookLive.channelName,
//            MyApp.sp.getInt("userId", 0),
//            options
//        )
        //binding.localVideoViewContainerWatch.visibility=View.GONE

        mRtcEngine?.joinChannel(
            lookLive.headPic,
            lookLive.nickName,
            MyApp.sp.getInt("userId", 0),
            options
        )

        mRtcEngine?.joinChannel(token, channelName, 0, options)
    }

    //设置远端视图
    private fun setupRemoteVideo(uid: Int) {
        val container = findViewById<FrameLayout>(R.id.sv)
        val surfaceView = SurfaceView(this)
        surfaceView.setZOrderMediaOverlay(true)
        container.addView(surfaceView)
        // 将 SurfaceView 对象传入声网实时互动 SDK，设置远端视图
//        Log.e("====okhttp 设置远端视图2", "${uid}")
        mRtcEngine?.setupRemoteVideo(
            VideoCanvas(
                surfaceView, VideoCanvas.RENDER_MODE_FIT, uid
            )
        )
    }

    fun startVideo(){
        // 启用视频模块
        mRtcEngine!!.enableVideo()

// 创建一个 SurfaceView 对象，并将其作为 FrameLayout 的子对象
        val container = findViewById<FrameLayout>(R.id.sv)
        val surfaceView = SurfaceView(this)
        container.addView(surfaceView)
// 将 SurfaceView 对象传入声网实时互动 SDK，设置本地视图
        mRtcEngine!!.setupLocalVideo(VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_FIT, 0))

// 开启本地预览
        mRtcEngine!!.startPreview()
    }


    //初始化 RtcEngine 引擎
    fun initRtcEngine(){
        // 创建 RtcEngineConfig 对象，并进行配置
        val config = RtcEngineConfig().apply {
            mAppId = appId
            mContext = getBaseContext()
            mEventHandler = mRtcEventHandler
        }

// 创建并初始化 RtcEngine
        mRtcEngine = RtcEngine.create(config)

        // 启用视频模块
        mRtcEngine?.enableVideo()
    }



    fun settingLiveType(uid: Int, reason: Int){
        // 创建 ChannelMediaOptions 对象，并进行配置
        options=ChannelMediaOptions()

// 设置用户角色为 BROADCASTER (主播) 或 AUDIENCE (观众)
        options!!.clientRoleType = Constants.CLIENT_ROLE_AUDIENCE

// 设置频道场景为 BROADCASTING (直播场景)
        options!!.channelProfile = Constants.CHANNEL_PROFILE_LIVE_BROADCASTING

// 发布麦克风采集的音频
        options!!.publishMicrophoneTrack = true

// 发布摄像头采集的视频
        options!!.publishCameraTrack = true

// 自动订阅所有音频流
        options!!.autoSubscribeAudio = true

// 自动订阅所有视频流
        options!!.autoSubscribeVideo = true

// 使用临时 Token 和频道名加入频道，uid 为 0 表示引擎内部随机生成用户名
// 成功后会触发 onJoinChannelSuccess 回调
        mRtcEngine!!.joinChannel(token, channelName, 0, options)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mRtcEngine != null) {
            // 停止本地视频预览
            mRtcEngine!!.stopPreview();
            // 离开频道
            mRtcEngine!!.leaveChannel();
            mRtcEngine = null;
            // 销毁引擎
            RtcEngine.destroy();
        }
    }

    // 获取体验实时音视频互动所需的录音、摄像头等权限
    private fun getRequiredPermissions(): Array<out String> {
        // 判断 targetSDKVersion 31 及以上时所需的权限
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            arrayOf(
                Manifest.permission.RECORD_AUDIO,  // 录音权限
                Manifest.permission.CAMERA,  // 摄像头权限
                Manifest.permission.READ_PHONE_STATE,  // 读取电话状态权限
                Manifest.permission.BLUETOOTH_CONNECT // 蓝牙连接权限
            )
        } else {
            arrayOf(
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.CAMERA
            )
        }
    }

    private fun checkPermissions(): Boolean {
        for (permission in getRequiredPermissions()!!) {
            val permissionCheck = ContextCompat.checkSelfPermission(this, permission)
            if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                return false
            }
        }
        return true
    }

    //md5 加密
    fun md5Encrypt(input: String): String {
        return try {
            // 获取MessageDigest实例
            val digest = MessageDigest.getInstance("MD5")

            // 更新MessageDigest对象
            digest.update(input.toByteArray())

            // 获取哈希值
            val hash = digest.digest()

            // 将哈希值转换为十六进制字符串
            hash.joinToString("") { "%02x".format(it) }
        } catch (e: NoSuchAlgorithmException) {
            throw RuntimeException("Error generating MD5 hash", e)
        }
    }

}
